package com.example.result.dao.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.result.dao.api.DaoApi
import com.example.result.dao.api.PullState
import com.example.result.dao.db.DaoDb
import com.example.result.dao.vo.DaoDatas
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject

@HiltViewModel
class DaoViewModel @Inject constructor(val db: DaoDb, val api: DaoApi) : ViewModel() {
    val stateData by lazy {
        MutableLiveData<PullState>()
    }

    fun refreshSectionData() {

        api.getData(0).enqueue(object : Callback<DaoDatas> {
            override fun onFailure(call: Call<DaoDatas>, t: Throwable) {
                stateData.value = PullState.FAILURE
            }

            override fun onResponse(
                call: Call<DaoDatas>,
                response: Response<DaoDatas>
            ) {
                viewModelScope.launch {
                    var state = PullState.FAILURE
                    if (response.isSuccessful) {
                        withContext(Dispatchers.IO) {
                            response.body()?.data?.let { it ->
                                db.sectionDao().insertSection(it)
                                for (section in it) {
                                    section.data.map {
                                        it.sectionId = section.id
                                        it
                                    }.let {
                                        db.contentDao().insert(it)
                                    }
                                }
                            }
                            Log.d("Dispatchers", "1")

                        }
                        state = PullState.SUCCESS

                    }
                    if (isActive) {
                        stateData.value = state
                    }
                    Log.d("Dispatchers", "2")
                }
                Log.d("Dispatchers", "3")
            }
        }
        )
    }
}